#include "Avalon/Network/SocketThreadPool.hpp"
#define _WIN32_WINNT 0x0501
#include <boost/asio.hpp>
#pragma warning(disable : 4267)
#include <boost/thread.hpp>
#pragma warning(default : 4267)

using namespace Avalon;
using namespace Avalon::Network;
using namespace boost;
using namespace boost::asio;
using namespace std;

SocketThreadPool::~SocketThreadPool() {
  m_work.reset();
  m_service.stop();
  while(!m_threads.empty()) {
    thread* serviceThread = m_threads.back();
    m_threads.pop_back();
    serviceThread->join();
    delete serviceThread;
  }
}

io_service& SocketThreadPool::GetService() {
  return m_service;
}

SocketThreadPool::SocketThreadPool()
    : m_work(new io_service::work(m_service)) {
  static const int SOCKET_THREADS = static_cast<int>(
    thread::hardware_concurrency());
  for(int i = 0; i < SOCKET_THREADS; ++i) {
    thread* serviceThread = new thread(bind(&io_service::run, ref(m_service)));
    m_threads.push_back(serviceThread);
  }
}
